package com.rsa.encrypt.sign;

import com.rsa.tools.RsaTools;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;

/**
 * @author lf
 * @Description: 数据加签
 * @date 2020/7/30 12:38
 */
public class EncryptSign {

    private static final Logger log = LoggerFactory.getLogger(EncryptSign.class);
    /**
     * 数据加签
     * @param data  待加签数据
     * @param privateKey    请求放私钥
     * @return  加签后的内容
     * @throws Exception
     */
    public static String sign(String data, String privateKey) throws Exception {
        log.info("对外提供的数据加签方法...");
        return sign(data, RsaTools.getPrivateKey(privateKey));
    }

    /**
     * 签名
     *
     * @param data 待签名数据
     * @param privateKey 私钥
     * @return 签名
     */
    public static String sign(String data, PrivateKey privateKey) throws Exception {
        byte[] keyBytes = privateKey.getEncoded();
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey key = keyFactory.generatePrivate(keySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initSign(key);
        signature.update(data.getBytes());
        return new String(Base64.encodeBase64(signature.sign()));
    }
}
